package functions

import (
	"fmt"

	"github.com/project-flogo/core/data"
	"github.com/project-flogo/core/data/coerce"

	"github.com/project-flogo/core/data/expression/function"
)

func init() {
	err := function.Register(&fnArraySlice{})
	if err != nil {
		panic(err)
	}
}

type fnArraySlice struct{}

func (fnArraySlice) Name() string {
	return "arraySlice"
}

func (fnArraySlice) Sig() (paramsTypes []data.Type, isVariadic bool) {
	return []data.Type{data.TypeArray, data.TypeInt, data.TypeInt}, false
}

func (fnArraySlice) Eval(params ...interface{}) (interface{}, error) {
	payload, err := coerce.ToArray(params[0])
	if err != nil {
		return nil, fmt.Errorf("arraySlice function parameter 0 must be array, got %t", params[0])
	}
	start, err := coerce.ToInt(params[1])
	if err != nil {
		return nil, fmt.Errorf("arraySlice funtion parameter 1 must be int, got %+v", params[1])
	}
	end := len(payload)
	if len(params) == 3 {
		end, err = coerce.ToInt(params[2])
		if err != nil {
			return nil, fmt.Errorf("arraySlice funtion parameter 2 must be int, got %+v", params[2])
		}
	}
	n := payload[start:end]
	return n, nil
}
